#required modules: identify, ImageMagick

size=$1
src_file=$2
dst_file=$3
size_opt="$size"x"$size"

#<<1>>. resize the image to let the short-side become 256 pixel. Aspect ratio preserved.
convert $src_file -resize $size_opt^ $dst_file

#<<2>>. crop the long-side to make it 256 pixel. The preserved region is at the center of image. 
width=$(identify $dst_file | awk '{print $3}' | cut -d'x' -f 1)
height=$(identify $dst_file | awk '{print $3}' | cut -d'x' -f 2)
if [ "$width" -eq "$size" ]; then
# height is the long-side. Calculte how much it should be cropped.
  crop_size=$(($height - $size))
  crop_size_1=$(($crop_size / 2))
  mogrify -crop $size_opt+0+$crop_size_1 $dst_file
#  crop_size_2=$(($crop_size - $crop_size_1))  
#  convert test.JPEG -crop $size_opt+0+$crop_size_1 test2.JPEG
else
# width is the long-side. Calculte how much it should be cropped.
  crop_size=$(($width - $size))
  crop_size_1=$(($crop_size / 2))
  mogrify -crop $size_opt+$crop_size_1+0 $dst_file
#  crop_size_2=$(($crop_size - $crop_size_1))
#  convert test.JPEG -crop $size_opt+$crop_size_1+0 test2.JPEG
fi


